<?php

namespace app\admin\model\course;

use app\admin\model\User;
use app\admin\model\user\School;
use app\admin\model\UserCollection;
use think\Model;


class Course extends Model
{





    // 表名
    protected $name = 'course';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }


    public function category()
    {
        return $this->belongsTo('app\admin\model\user\TeacherCategory', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function tags()
    {
        return $this->belongsTo('app\admin\model\course\Tags', 'tags', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public static function getTags($tags){
        if(!empty($tags)){
            $tagsIds = explode(",", $tags);
            return Tags::where("id","in", $tagsIds)->column("name");
        }
        return  "";

    }


    /*
     * 获取课程配置
     * $mode  1 所有 2 开启的
     * */
    public function getCourseConfig($mode = 1){
        $classesConfigModel = new \app\admin\model\course\ClassesConfig();
        $defaultConfig = $classesConfigModel->getDefaultConfig();
        $rowConfig = json_decode($this["config"], true);

//        dump($rowConfig);exit;
        $schoolArr = [];
        $classesArr = [];
        $timeArr = [];
        foreach ($rowConfig as $rowSchoolKey => $rowSchool){
            //学校是否开启
//            dump($rowSchool);exit;
            if(isset($rowSchool['switch']) && $rowSchool['switch'] == 1){
                $schoolArr[$rowSchoolKey] = [
                    "switch" => 1
                ];
            }
            foreach ($rowSchool['classes'] as $rowClassesKey => $rowClasses){
                //班级是否开启
                if(isset($rowClasses['switch']) && $rowClasses['switch'] == 1){
                    $classesArr[$rowSchoolKey."_".$rowClassesKey] = [
                        "switch" => 1
                    ];
                }
//                dump($rowClasses);exit;
                foreach ($rowClasses['time'] as $rowTimeKey => $rowTime){
                    if(isset($rowTime['switch']) && $rowTime['switch'] == 1){
                        $timeArr[$rowSchoolKey."_".$rowClassesKey."_".$rowTimeKey] = [
                            "switch"=> 1,
                            "teacher_id"=> $rowTime["teacher_id"]??0,
                            "student_num"=> $rowTime["student_num"]??0,
                        ];
                    }

                }
            }
        }
//        dump($rowConfig);

//        dump($schoolArr);
//        dump($classesArr);
//        dump($timeArr);
//        dump($defaultConfig);
//        exit;



        foreach ($defaultConfig as $schoolKey => &$school){
            if(isset($schoolArr[$school['school_id']]) && $schoolArr[$school['school_id']]["switch"] == 1){
                $school["switch"] = 1;
            }else{
                if($mode == 2){
                    unset($defaultConfig[$schoolKey]);
                    continue;
                }else{
                    $school["switch"] = 0;
                }

            }
            foreach ($school['data'] as $classesKey => &$class){
                if(isset($classesArr[$school['school_id']."_".$class["classes_id"]]) && $classesArr[$school['school_id']."_".$class["classes_id"]]["switch"] == 1){
                    $class["switch"] = 1;
                }else{
                    if($mode == 2){
                        unset($defaultConfig[$schoolKey]['data'][$classesKey]);
                        continue;
                    }else{
                        $class["switch"] = 0;
                    }

                }

                foreach ($class['data'] as $timeKey => &$timeValue){

                    foreach ($timeValue['config'] as $configKey => &$configValue){
                        if(isset($timeArr[$school['school_id']."_".$class["classes_id"]."_".$timeValue['w']."_".$configValue['time_no']]) && $timeArr[$school['school_id']."_".$class["classes_id"]."_".$timeValue['w']."_".$configValue['time_no']]['switch'] == 1){
                            $configValue['switch'] = 1;
                            $teacher_id = $timeArr[$school['school_id']."_".$class["classes_id"]."_".$timeValue['w']."_".$configValue['time_no']]['teacher_id']??0;
                            $configValue['teacher_id'] = $teacher_id;
                            $configValue['teacher_name'] = User::where("id",$teacher_id)->value("nickname")??'';
                            $configValue['student_num'] = $timeArr[$school['school_id']."_".$class["classes_id"]."_".$timeValue['w']."_".$configValue['time_no']]['student_num']??0;
                            $buy_num = OrderGoods::where([
                                "course_id" => $this['id'],
                                "school_id" => $school['school_id'],
                                "classes_id" => $class["classes_id"],
                                "w" => $timeValue['w'],
                                "time_no" => $configValue['time_no'],
                                "status" => [">=", Order::STATUS_PAY]
                            ])->count();
                            $configValue['buy_num'] = $buy_num;
                        }else{
                            if($mode == 2){
                                unset($defaultConfig[$schoolKey]['data'][$classesKey]['data'][$timeKey]['config'][$configKey]);
                                continue;
                            }else{
                                $configValue['switch'] = 0;
                                $configValue['teacher_id'] = '';
                                $configValue['teacher_name'] = '';
                                $configValue['student_num'] = 0;
                                $configValue['buy_num'] = 0;
                            }

                        }
                    }
                    if($mode == 2 && isset($timeValue['config']) && count($timeValue['config']) == 0){
                        unset($defaultConfig[$schoolKey]['data'][$classesKey]['data'][$timeKey]);
                    }


                }
            }
        }

//        dump($defaultConfig);
//        dump($rowConfig);
//        exit;
        return $defaultConfig;

    }




    /*
     * 获取课程列表
     * */
    public function getList($condition = [],$paginate = 1, $limit = 15){
        $list = $this->where("switch",1)
            ->where($condition)
            ->field("config,content",true);
        if($paginate == 1){
            $list = $list->paginate();
        }else{
            $list = $list->limit($limit)->select();
        }
        foreach ($list as $key => &$value){
            $value = $this->dealInfo($value);
        }
        return $list;
    }


    /*
     * 获取详情
     * */
    public function getInfo($condition = [],$user = null,$lat = '', $lng=''){
        $no_school_id = 0;
        $school_id = 0;

        if(isset($condition['no_school_id'])){
            $no_school_id = $condition['no_school_id'];
            unset($condition['no_school_id']);
        }
        if(isset($condition['school_id'])){
            $school_id = $condition['school_id'];
            unset($condition['school_id']);
        }

//        dump($no_school_id);
//        dump($school_id);exit;

        $info = $this->where($condition)
            ->where("switch",1)
            ->find();
        if(!$info){
            exception("未找到当前课程");
        }
        $info = $this->dealInfo($info);
        $config = $info->getCourseConfig(2);
        if($no_school_id > 0){
            foreach ($config as $schoolKey => $schoolValue){
                if($schoolValue['school_id'] == $no_school_id){
                    unset($config[$schoolKey]);
                }
            }
        }
        if($school_id > 0){
            foreach ($config as $schoolKey => $schoolValue){
                if($schoolValue['school_id'] != $school_id){
                    unset($config[$schoolKey]);
                }
            }
        }

        if(!empty($lat) && !empty($lng)){
            foreach ($config as $key=>&$schoolValue){
                $schoolValue['distance'] = calculationDistance($lat, $lng, $schoolValue['lat'], $schoolValue['lng']);
            }
        }


        $info['config'] = $config;
        $userCollectionModel = new UserCollection();
        $info["is_collection"] = $userCollectionModel->checkUserCollection($user,$info['id'],$userCollectionModel::TYPE_COURSE);
        return $info;
    }



    /*
     * 处理详情
     * */
    public function dealInfo($info){
        $info['image'] = deal_img_url($info['image']);

        return $info;
    }

    /*
     * 预下单
     * */
    public function preOrder($type,$data_id, $coupon_id = 0,$user_id = 0,$pay_type="wechat",$is_pay = false){
        $money = 0; // 计算原价
        $course_price = 0; // 课程价格
        $discount_money = 0;
        $vip_discount_money = 0;
        $course = [];
        switch ($type){
            case Order::TYPE_ADMIN://后台录单
            case Order::TYPE_RESTORE://后台录单
            case Order::TYPE_TRANSFER://后台录单
                $course = $this->getInfo(["id"=>$data_id]);
                $money = $course['price'];
                $course_price = $course['price'];
                break;
            case Order::TYPE_COURSE://普通订单
                $course = $this->getInfo(["id"=>$data_id]);
                $money = $course['price']; //原价
                $course_price = $course['price']; //课程价格
                $userCouponModel = new \app\admin\model\course\UserCoupon();
                if($coupon_id > 0){
                    $couponInfo = $userCouponModel->checkUserCoupon($coupon_id,$user_id,$is_pay);
                    if($money >= $couponInfo['money']){
                        $discount_money = $couponInfo['reduction_money']; // -5    0.5
                        $money = bcsub($money,$discount_money,2);

                    }
                }
                //如果是Vip的话 打折 只有 余额支付会打折
                $is_vip = User::where("id",$user_id)->value("is_vip")??0;
                if($is_vip && $pay_type == 'money'){
                    $vip_discount = config("site.vip_discount")??10;
                    $vip_price =  bcmul($money,($vip_discount/10),2);
                    $vip_discount_money = bcsub($money,$vip_price,2);
                    $money = $vip_price;

                }

                break;
            case Order::TYPE_SPELL://拼团订单 不能用优惠券
                $spellModel = new Spell();
                $spell = $spellModel->getInfo(["id"=>$data_id]);
//                $course = $spell['course'];
                $money = $spell['spell_price'];
                $course_price = $spell['spell_price'];
                break;
        }

        if($money < 0){
            exception("配置错误，请联系管理员");
        }
        $coupon = new \app\admin\model\course\Coupon();
        $coupon_count = $coupon->getUserCouponCount($user_id,$course_price);

        $res = [
            "price" => $course_price,
            "discount_money" => $discount_money,
            "money" => $money,
            "vip_discount_money" => $vip_discount_money,
            "coupon_count" => $coupon_count,
//            "course" => $course
        ];

        return $res;
    }


    /*
     * 删除课程
     * */
    public function delCourse(){
        //检测当前学员下面是否有正在进行的课程
        $course_order = Order::where("course_id",$this['id'])->where("status","in",Order::getInStatusArr())->find();
        if($course_order){
            exception($this['name']."存在正在进行的订单，无法删除");
        }
        $this->delete();
        return true;
    }
}
